package com.todo.controller;

import com.todo.common.Result;
import com.todo.dto.TodoRequest;
import com.todo.entity.Todo;
import com.todo.service.TodoService;
import com.todo.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 待办事项控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/todo")
@CrossOrigin(origins = "*")
public class TodoController {

    @Autowired
    private TodoService todoService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 创建待办事项
     */
    @PostMapping
    public Result<Todo> createTodo(@Valid @RequestBody TodoRequest request, HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            Todo todo = todoService.createTodo(userId, request);
            return Result.success("创建成功", todo);
        } catch (Exception e) {
            log.error("创建待办事项失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新待办事项
     */
    @PutMapping
    public Result<Todo> updateTodo(@Valid @RequestBody TodoRequest request, HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            Todo todo = todoService.updateTodo(userId, request);
            return Result.success("更新成功", todo);
        } catch (Exception e) {
            log.error("更新待办事项失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除待办事项
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteTodo(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            todoService.deleteTodo(userId, id);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除待办事项失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 完成待办事项
     */
    @PutMapping("/{id}/complete")
    public Result<String> completeTodo(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            todoService.completeTodo(userId, id);
            return Result.success("任务已完成");
        } catch (Exception e) {
            log.error("完成待办事项失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 取消完成待办事项
     */
    @PutMapping("/{id}/uncomplete")
    public Result<String> uncompleteTodo(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            todoService.uncompleteTodo(userId, id);
            return Result.success("任务已恢复");
        } catch (Exception e) {
            log.error("取消完成待办事项失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取待办事项列表
     */
    @GetMapping
    public Result<List<Todo>> getTodoList(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            List<Todo> todos = todoService.getTodoList(userId, status, keyword);
            return Result.success(todos);
        } catch (Exception e) {
            log.error("获取待办事项列表失败", e);
            return Result.error("获取待办事项列表失败");
        }
    }

    /**
     * 搜索待办事项
     */
    @GetMapping("/search")
    public Result<List<Todo>> searchTodos(
            @RequestParam String keyword,
            @RequestParam(required = false) Integer status,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            List<Todo> todos = todoService.searchTodos(userId, keyword, status);
            return Result.success(todos);
        } catch (Exception e) {
            log.error("搜索待办事项失败", e);
            return Result.error("搜索失败");
        }
    }

    /**
     * 根据日期获取待办事项
     */
    @GetMapping("/date/{date}")
    public Result<List<Todo>> getTodosByDate(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            List<Todo> todos = todoService.getTodosByDate(userId, date);
            return Result.success(todos);
        } catch (Exception e) {
            log.error("根据日期获取待办事项失败", e);
            return Result.error("获取待办事项失败");
        }
    }

    /**
     * 根据ID获取待办事项详情
     */
    @GetMapping("/detail/{id}")
    public Result<Todo> getTodoById(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            Todo todo = todoService.getTodoById(userId, id);
            return Result.success(todo);
        } catch (Exception e) {
            log.error("获取待办事项详情失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取待办事项统计
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getTodoStatistics(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            Map<String, Object> statistics = todoService.getTodoStatistics(userId);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取待办事项统计失败", e);
            return Result.error("获取统计信息失败");
        }
    }

    /**
     * 获取今天、明天、后天的待办事项
     */
    @GetMapping("/grouped")
    public Result<Map<String, List<Todo>>> getTodosGroupByDate(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            Map<String, List<Todo>> groupedTodos = todoService.getTodosGroupByDate(userId);
            return Result.success(groupedTodos);
        } catch (Exception e) {
            log.error("获取分组待办事项失败", e);
            return Result.error("获取待办事项失败");
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            return jwtUtil.getUserIdFromToken(token);
        }
        throw new RuntimeException("未授权访问");
    }
} 